<template>
  <div>
    <input
      type="text"
      v-model="searchQuery"
      @input="searchProducts"
      placeholder="Search"
    />
    <ul>
      <li v-for="product in products" :key="product.id">{{ product.name }}</li>
    </ul>
    <button @click="onPageChange(pageIndex - 1)" :disabled="pageIndex === 1">
      Previous
    </button>
    <span>{{ pageIndex }}</span>
    <button
      @click="onPageChange(pageIndex + 1)"
      :disabled="pageIndex === totalPages"
    >
      Next
    </button>
  </div>
</template>

<script>
import { ref, watch } from "vue";
import axios from "axios";

export default {
  setup() {
    const products = ref([]);
    const pageIndex = ref(1);
    const pageSize = 10;
    const searchQuery = ref("");

    // 获取商品数据
    const getProducts = () => {
      const url = `http://127.0.0.1:1234/Dd/pager?pageNum=${pageIndex.value}&pageSize=${pageSize}&search=${searchQuery.value}`;

      axios
        .get(url)
        .then((response) => {
          products.value = response.data;
        })
        .catch((error) => {
          console.error("Error:", error);
        });
    };

    // 搜索商品
    const searchProducts = () => {
      pageIndex.value = 1;
      getProducts();
    };

    // 分页切换
    const onPageChange = (page) => {
      pageIndex.value = page;
      getProducts();
    };

    // 监听 pageIndex 和 searchQuery 的变化
    watch([pageIndex, searchQuery], () => {
      getProducts();
    });

    return {
      products,
      pageIndex,
      searchQuery,
      totalPages: Math.ceil(products.length / pageSize),
      getProducts,
      searchProducts,
      onPageChange,
    };
  },
};
</script>
